<?php 
/**
 * 购物车管理控制器
 */
 
 class CartsController extends CommonController{
 	//用户是否登录判断、
 	public function __init(){
 		parent::__init();
		if(!isset($_SESSION['uid'])) $this->error('请登录用户');
		
 	}
	
	public function index(){
		//获取购物车数据
		$cartData = cart::getAllData();
		$this->assign('cartData',$cartData);
		$this->navigation();
		$this->display();
	}
	
	/**
	 * 异步添加购物车
	 */
	public function addCart(){
		if(!isset($_SESSION['uid'])) $this->error('请登录用户');
		$gid = Q('post.gid');
		$specId = explode(',', rtrim(Q('post.specId'),','));
		$goodsData = K('goods')->where("gid={$gid}")->find();
		//获取图片(获取商品详情表的缩略图)
		$goodsDetail = K('GoodsDetail')->where("goods_gid={$gid}")->find();
		//获取规信息
		$spec = array();
		foreach ($specId as $v) {
			$spec[] = M('')->join('goods_attr as ga JOIN type_attr as ta ON ta.taid = ga.type_attr_taid')->where("ga.gaid={$v}")->find();
		}
		$option = array();
		foreach ($spec as $k => $v) {
			$option[$v['taname']] = $v['gvalue'];
		}
		//组合$data的参数
		$data = array(
			'id'      => Q('post.gid'),
			'name'    => $goodsData['gname'],
			'num'     => Q('post.num'),
			//price 为单价
			'price'   => Q('post.tolprice'),
			'options' => $option,
			'smallImg' => $goodsDetail['smallpic'],
			'specId'   => Q('post.specId')
		);
		cart::add($data);
		//返回当前添加的到购物车的sid
		$sid = array_keys($_SESSION['cart']['goods']);
		$sid = array_pop($sid);
		echo $sid;die;

	}
	
	
	/**
	 * 异步获取数量更新购物车
	 */
	public function ajaxUpdateCart(){
		if(!IS_AJAX) $this->error('非法请求');
		$data = array(
			'sid' => Q('post.sid'),
			'num' => Q('post.num')
		);
		cart::update($data);
		
	}

	/**
	 * 异步删除购物车
	 */
	public function deleteCart(){
		if(!IS_AJAX) $this->error('非法请求');
		$sid = Q('post.sid');
		unset($_SESSION['cart']['goods'][$sid]);
		echo 1;die;
	}
	
	
	
 }















 ?>